<?php

class UsersController extends AppController {

    var $name = 'Users';
    
    var $helpers = array('Form');
    
    function beforeFilter() {
        $this->Auth->allow(array('register', 'logout'));
    }
    
    function isAuthorized() {
        return true;
    }
    
    /**
     *  The AuthComponent provides the needed functionality
     *  for login, so you can leave this function blank.
     */
    function login() {
        if ($this->Auth->login()) {
            $user = $this->User->find('first', array(
                                        'conditions' => "User.username = {$this->data['username']}"
            ));
            $this->Session->write('User.UserID', $user['User']['id']);
            
            $this->redirect($this->Auth->redirect());
        } else {
            if(!($this->data))
                $this->Session->setFlash('Area riservata, effettuare il login');
            else
                $this->Session->setFlash('Email o password errati, si prega di riprovare');
        }
    }

    function logout() {
        $this->redirect($this->Auth->logout());
    }
    
    function register() {
        if (!empty($this->data) && $this->User->validates()){
            
            $user = $this->User->find('first', array(
                                         'conditions' => array(
                                             'User.username' => $this->data['User']['username']
                                         )
                                     )
            );
            
            if(empty($user)) {
                if ($this->User->save($this->data)) {
                    $this->Auth->login($this->data);
                    $this->Session->setFlash('Account utente creato con successo');
                    $this->redirect(array('controller' => 'people', 'action' => 'add', $this->data['User']['username']));
                }
            }
            else {
                $this->Session->setFlash('Esiste già un utente con questo indirizzo email');
                $this->redirect(array('controller' => 'users', 'action' => 'register'));
            }
            
        }
    }
}

?>